package com.sto.stoapp.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.dataprocess.ProcessUploadData;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.UploadDataManager;
import com.sto.stoapp.file.SmzFile;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.LockScreenManager;
import com.sto.stoapp.manager.UnSentDataManager;
import com.sto.stoapp.manager.UnSentPictureManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

/**
 * 基类
 *
 * @author mgf
 */
@SuppressLint("HandlerLeak")
public class BaseActivity extends Activity {

    private static final String UPDATE_SYNCH = "update_synch";
    public static final String CLOSE_THIS_ACTIVITY_ACTION = "close_this_activity_action";
    // 更新未发数据
    public static final int UPDATE_SEND = 0x67;
    // 未发数据广播事件
    public static final String SEND_ACTION = "send_action";
    // 传递未发数据量
    public static final String SEND_COUNT = "send_count";

    // 更新订单显示
    public static final String REFRESH_ORDER_ACTION = "refresh_order_action";

    private TextView unsentText, unsentPictureText, slashText, notText;

    // 未发数据
    private int unSent;

    private SendBroad sendBroad;
    private boolean is520Device = false;

    private boolean isSaveData = false;
    // 扫描上传表
    private ArrayList<Integer> uploadTables = null;
    BluetoothAdapter BTAdapter;
    CloseReceiver mcloseReceiver;


    protected SmzFile smzfile = null;

    protected boolean checkSiteZJ() {
        if (smzfile == null) {
            smzfile = new SmzFile(this);
        }
        return smzfile.findIsZJSiteCode(StoFilePreference.getInstance(this)
                .getSiteCode());
    }

    protected void addUploadTable(EnumTableNames item) {
        if (uploadTables == null) {
            uploadTables = new ArrayList<Integer>();
        }
        if (!uploadTables.contains(item.ordinal())) {
            uploadTables.add(item.ordinal());
        }
    }

    protected List<EnumTableNames> getUploadTable() {
        if (uploadTables == null) {
            return null;
        }
        List<EnumTableNames> tables = new ArrayList<EnumTableNames>();
        for (Integer i : uploadTables) {
            tables.add(EnumTableNames.values()[i]);
        }
        return tables;
    }

    public boolean isSaveData() {
        return isSaveData;
    }

    public void setSaveData(boolean isSaveData) {
        this.isSaveData = isSaveData;
    }

    private BaseDialog dialog;

    public void sendData() {
        Intent intent = new Intent(UnifiedStaticType.UP_ACTION);
        intent.putIntegerArrayListExtra(UnifiedStaticType.UPLOAD_TYPE,
                new ProcessUploadData().sendAllData());
        sendBroadcast(intent);
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == UPDATE_SEND) {
                updateSend(msg.arg1);
            }
        }
    };

    public boolean getSecurityPackageInfo() {
        PackageManager packageManager = this.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo("kaicom.com.security", PackageManager.GET_META_DATA);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return packageInfo == null ? false : true;
    }

    private void updateSend(int count) {
        synchronized (UPDATE_SYNCH) {

            unSent = UnSentDataManager.getInstance().getUnSent() - count;
            if (unSent < 0) {
                unSent = 0;
            }

            // 显示扫描个数
            if (unsentText != null) {
                unsentText.setText(unSent + "");
                System.out.println(unSent + "未发");
            }

            // 显示图片个数
            if (unsentPictureText != null) {
                // 假如数据小于0,强制设置为0
                if (UnSentPictureManager.getInstance(this).getUnSent() < 0) {
                    UnSentPictureManager.getInstance(this).setUnSent(0);
                }
                unsentPictureText.setText(UnSentPictureManager
                        .getInstance(this).getUnSent() + "");
            }

            // UnSentDataManager.getInstance().setUnSent(unSent);

        }
    }

    // private void setUpdateSend(int count) {
    // synchronized (UPDATE_SYNCH) {
    // int tmpCount = count;
    // if(tmpCount < 0){
    // tmpCount = 0;
    // }
    // if (unsentText != null) {
    // unsentText.setText(unSent + "未");
    // }
    // UnSentDataManager.getInstance().setUnSent(tmpCount);
    //
    // }
    // }

    public void addCodeNumber() {
        UnSentDataManager.getInstance().addCodeNumber();
        updateSend(0);
    }

    public void addCodeNumber(int count) {
        updateSend(0);
    }

    public void deleteCodeNumber() {
        UnSentDataManager.getInstance().deleteCodeNumber();
        updateSend(0);
    }

    public void deleteCodeNumber(int count) {
        UnSentDataManager.getInstance().deleteCodeNumber(count);
        updateSend(0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);

        Log.d("wj","当前打开的是："+getClass().getSimpleName());

        BTAdapter = BluetoothAdapter.getDefaultAdapter();
        is520Device = StoApplication.DeviceModel_520.equals(new Build().MODEL
                .trim())
                || StoApplication.DeviceModel_521.equals(new Build().MODEL
                .trim());
        IntentFilter f = new IntentFilter(CLOSE_THIS_ACTIVITY_ACTION);
        mcloseReceiver = new CloseReceiver();
        registerReceiver(mcloseReceiver, f);

    }

    private void initWidget() {
        try {
            unsentText = (TextView) findViewById(R.id.un_send);
            unsentPictureText = (TextView) findViewById(R.id.un_send_picture);
            slashText = (TextView) findViewById(R.id.slash_text);
            notText = (TextView) findViewById(R.id.not_text);
            // uploadGif = (GifView) findViewById(R.id.upload_flag);
            // uploadGif.setGifImage(R.drawable.upload_flag);
            // uploadGif.setVisibility(View.GONE);
            unsentText
                    .setText("" + UnSentDataManager.getInstance().getUnSent());
            unsentPictureText.setVisibility(View.GONE);
            // unsentPictureText.setText(""
            // + UnSentPictureManager.getInstance(this).getUnSent());
            // slashText.setText("/");
            notText.setText("未");

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionLog.writeLog("unsentText", e.getMessage());
        }

    }

    public void setStoTitle(int id) {
        try {
            initWidget();
            TextView title = ((TextView) findViewById(R.id.title));

            StringBuffer sb = new StringBuffer();
            sb.append(getText(id)).append("(")
                    .append(StoFilePreference.getInstance(this).getUserName())
                    .append(")");
            title.setText(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setStoTitle(String name) {
        try {
            initWidget();
            TextView title = ((TextView) findViewById(R.id.title));

            StringBuffer sb = new StringBuffer();
            sb.append(name).append("(")
                    .append(StoFilePreference.getInstance(this).getUserName())
                    .append(")");
            title.setText(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isDigit(String str) {
        return str.matches("[0-9]+");
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        System.out.println("onKeyUp keyCode:"+keyCode);
        keyCode=StoApplication.getStoJni().getEventFuction(keyCode);
        switch (keyCode) {
            case StoPdaKeyEvent.KEYCODE_F1:
                if(Helper.isK7()){
                    isPressFn = false;
                }else{
                    doUploadData();
                    return true;
                }

                return super.onKeyUp(keyCode, event);

            case StoPdaKeyEvent.KEYCODE_F4: // F4
                // 关闭锁 解锁
                if (StoFilePreference.getInstance(BaseActivity.this)
                        .getlockTouchScreen()) {

                    StoApplication.getStoJni().Enable_touch_screen();
                    Helper.showToast(this, getString(R.string.touch_screen_open));

                    LockScreenManager.getInstance().closeLockScreen();

                    StoFilePreference.getInstance(BaseActivity.this)
                            .setlockTouchScreen(false);
                }
                // 打开锁 锁住屏幕
                else {
                    Helper.showToast(this, getString(R.string.touch_screen_close));
                    StoApplication.getStoJni().Disable_touch_screen();
                    LockScreenManager.getInstance().createLockScreen(this);
                    // handler.sendEmptyMessageAtTime(HIDE_LOCK_SCREEN, 30000);
                    StoFilePreference.getInstance(BaseActivity.this)
                            .setlockTouchScreen(true);
                }
                return true;
            default:

                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void uploadBroadcast(ArrayList<Integer> uploadTables) {
        Intent intent = new Intent(UnifiedStaticType.UP_ACTION);
        intent.putIntegerArrayListExtra(UnifiedStaticType.UPLOAD_TYPE,
                uploadTables);
        sendBroadcast(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return super.onKeyDown(keyCode, event);
    }

    public void showNotice() {
        dialog = new BaseDialog(this);
        dialog.setTitles(getString(R.string.is_exit));
        if (isSaveData()) {
            if (unSent > 0) {
                isSaveData = true;
            } else {
                isSaveData = false;
                uploadTables = null;
            }
        }
        if (isSaveData) {
            dialog.setTitles(getString(R.string.is_exit_up_send));
        }
        if (!dialog.isShowing()) {
            dialog.show();
            dialog.getvMessage().setVisibility(View.GONE);
            dialog.getvPresentation().setVisibility(View.GONE);
            dialog.setOnBackClickListener(new OnBackClickListener() {

                @Override
                public void onBackClickListener(boolean res) {
                    // TODO Auto-generated method stub
                    if (isSaveData()) {
                        if (res) {
                            if (uploadTables != null) {
                                uploadBroadcast(uploadTables);
                                uploadTables = null;
                            } else {
                                sendData();
                            }
                        }
                        doBluetoothBack();

                    } else {
                        if (res) {
                            doBluetoothBack();
                        }
                    }

                }
            });
        } else {
            dialog.dismiss();
        }
    }

    protected void doBluetoothBack() {

        if (needSwitchBluetooth()) {
            dialog.dismiss();
            mBluetoothCloseOpenListener.listener();
            System.out.println("StoScanActivity  needSwitchBluetooth");
        } else {
            dialog.dismiss();

            System.out.println("StoScanActivity  !!!needSwitchBluetooth");
            finish();
        }
    }

    private boolean needSwitchBluetooth() {
        return is520Device && mBluetoothCloseOpenListener != null
                && BTAdapter.isEnabled();
    }

    BluetoothCloseOpenListener mBluetoothCloseOpenListener;

    protected void setBluetoothCloseOpenListener(
            BluetoothCloseOpenListener listener) {
        mBluetoothCloseOpenListener = listener;
    }

    public interface BluetoothCloseOpenListener {
        void listener();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //Add by wj 友盟统计
        MobclickAgent.onResume(this);
        //End by wj

        if (sendBroad == null) {
            sendBroad = new SendBroad();
            IntentFilter filter = new IntentFilter(SEND_ACTION);
            registerReceiver(sendBroad, filter);
        }
        // 其它界面也显示未发票数
        updateSend(0);
        if (StoFilePreference.getInstance(BaseActivity.this)
                .getlockTouchScreen()) {
            LockScreenManager.getInstance().createLockScreen(this);
            Helper.showToast(this, getString(R.string.touch_screen_close));
            // handler.sendEmptyMessageAtTime(HIDE_LOCK_SCREEN, 3000);
            StoApplication.getStoJni().Disable_touch_screen();
        } else {
            StoApplication.getStoJni().Enable_touch_screen();
            // Helper.showToast(this, getString(R.string.touch_screen_open));

            LockScreenManager.getInstance().closeLockScreen();
        }
    }

    @Override
    protected void onPause() {
        if (sendBroad != null) {
            unregisterReceiver(sendBroad);
            sendBroad = null;
        }
        // LockScreenManager.getInstance().closeLockScreen();
        super.onPause();

        //Add by wj
        MobclickAgent.onPause(this);
    }
    boolean isPressFn = false;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyCode=StoApplication.getStoJni().getEventFuction(event.getKeyCode());
        if (keyCode == StoPdaKeyEvent.KEYCODE_ENTER
                && event.getAction() == KeyEvent.ACTION_UP) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                v.performClick();
                return true;
            }
        } else if (keyCode == StoPdaKeyEvent.KEYCODE_F1
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            isPressFn = true;

        } else if (keyCode == StoPdaKeyEvent.KEYCODE_F1
                && event.getAction() == KeyEvent.ACTION_UP) {
            isPressFn = false;
        }
        if (isPressFn && keyCode == StoPdaKeyEvent.KEYCODE_1
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            doUploadData();
            return true;
        }

        return super.dispatchKeyEvent(event);
    }

    private void doUploadData() {
        Intent intent = new Intent(UnifiedStaticType.UP_ACTION);
        intent.putIntegerArrayListExtra(UnifiedStaticType.UPLOAD_TYPE,
                new ProcessUploadData().sendAllData());
        sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        if (sendBroad != null) {
            unregisterReceiver(sendBroad);
            sendBroad = null;
        }
        LockScreenManager.getInstance().closeLockScreen();
        if (mcloseReceiver != null) {
            unregisterReceiver(mcloseReceiver);
        }
        if (dialog != null) {
            dialog.dismiss();
        }

        if (uploadTables != null) {
            uploadTables = null;
        }
        handler.removeMessages(UPDATE_SEND);
        System.out.println("StoScanActivity : BaseActivity onDestroy");
        super.onDestroy();
    }

    public void initUnsentDataCount() {
        new StatisticsUnsendDataCountThread().start();
    }

    class StatisticsUnsendDataCountThread extends Thread {
        int countTemp = 0;

        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();

            countTemp = UploadDataManager.getInstance(BaseActivity.this)
                    .getUnsendDataCount();

            UnSentDataManager.getInstance().setUnSent(countTemp);

            Message msg = handler.obtainMessage();
            msg.what = UPDATE_SEND;
            msg.arg1 = 0;
            handler.sendMessage(msg);
        }
    }

    class SendBroad extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (arg1.getAction().equals(SEND_ACTION)) {
                int count = arg1.getIntExtra(SEND_COUNT, 0);
                Message msg = handler.obtainMessage();
                msg.what = UPDATE_SEND;
                msg.arg1 = count;
                handler.sendMessage(msg);
                // System.out.println("onReceive SendBroad" + count);
            }
        }
    }

    protected void closeBoard(EditText editText) {
        if (android.os.Build.VERSION.SDK_INT <= 10) {// 4.0以下 danielinbiti
            editText.setInputType(InputType.TYPE_NULL);
        } else {
            getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod(
                        "setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(editText, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    ProgressDialog pDialog;

    /**
     * 加载进度圈
     */
    public void showDialog() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                pDialog = new ProgressDialog(BaseActivity.this);
                pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                pDialog.setTitle(R.string.prompt);
                pDialog.setMessage(BaseActivity.this.getResources().getText(
                        R.string.request_update));
                pDialog.setCancelable(false);
                pDialog.show();

            }
        });

    }

    /**
     * 取消进度圈
     */
    public void cancelDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    public class CloseThread extends BaseThread {

        public CloseThread() {
            super(BaseActivity.this);

            showDialogByMessage("蓝牙处理中");
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();
            BTAdapter.disable();
            try {
                this.sleep(1000);
                BTAdapter.enable();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                cancelDialog();
                finish();
            }

        }

    }

    private void close() {
        finish();
    }

    protected class CloseReceiver extends BroadcastReceiver {

        public CloseReceiver() {
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (CLOSE_THIS_ACTIVITY_ACTION.equals(action)) {
                Helper.showToast(context, "24小时退出机制触发");
                close();
            }

        }

    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }
}
